package com.ssh.servlet;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ssh.service.LoginService;
import com.ssh.service.impl.LoginServiceImpl;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet.do")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("userName");
		String password = request.getParameter("password");
		String isCookie=null==request.getParameter("isCookie")?"no":request.getParameter("isCookie");
		//cookie操作
		if(Objects.equals(isCookie, "yes")) {
			Cookie cookie=new Cookie("nnblog","www.nnblog.com");
			cookie.setMaxAge(60*60*24);
			response.addCookie(cookie);
		}
		HttpSession session = request.getSession();
		LoginService loginService = new LoginServiceImpl();
		try {
			loginService.login(name, password);
			session.setAttribute("name", name);
			request.getRequestDispatcher("/WEB-INF/view/main.jsp").forward(request, response);
		} catch (Exception e) {
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

}
